import { routerRedux } from 'dva/router';
import { history } from 'umi';
import qs from 'querystring';

import {
    login,
    userAuth,
    loginOut,
    agentUserAuth,
    fetchSessionUser,
    getNewThirdAgent,
    setCompanyLogo,
    getWeather,
   
} from '../services/userService';
import { md5, encryptBy, decryptBy } from '../utils/encryption';
import moment from 'moment';

const companyReg = /\?pid\=0\.\d+&&userId=(\d+)&&companyId=(\d+)&&mode=(\w+)/;
const agentReg = /\?agent=(.*)/;
const agentReg2 = /iot-(.*)/;
let date = new Date();
// 初始化socket对象，并且添加监听事件
function createWebSocket(url, fromAgent, dispatch) {
    let ws = new WebSocket(url);
    // console.log(data);
    ws.onopen = function () {
        console.log('连接socket成功');
    };
    // ws.onclose = function(){
    //     console.log('socket close...');
    //     reconnect(url, data, companyId, dispatch);
    // };
    ws.onerror = function () {
        console.log('socket error...');
        reconnect(url, fromAgent, dispatch);
    };
    ws.onmessage = (e) => {
        if (dispatch) {
            if (e.data && e.data.length > 10) {
                let data = JSON.parse(e.data);
                dispatch({ type: 'user/setMsg', payload: { data: data.data } });
            }
        }
    };
    return ws;
}
let timer = null;
function reconnect(url, fromAgent, dispatch) {
    if (reconnect.lock) return;
    reconnect.lock = true;
    timer = setTimeout(() => {
        createWebSocket(url, fromAgent, dispatch);
        reconnect.lock = false;
    }, 5000);
}
let socket = null;
let menuMock = [
    {
        menuCode:'global_monitor',
        menuId:69,
        menuLevel:1,
        menuName:'监控中心',
        parentId:0,
        parentMenuName:null,
        subMenu:[
            {
                menuCode:'init_board',
                menuId:80,
                menuLevel:2,
                menuName:'高效机房大屏',
                parentId:69,
                parentMenuName:null,
                subMenu:[]
            },
            // {
            //     menuCode:'frozen_station',
            //     menuId:80,
            //     menuLevel:2,
            //     menuName:'制冷站',
            //     parentId:69,
            //     parentMenuName:null,
            //     subMenu:[]
            // },
            {
                menuCode:'canvas_board',
                menuId:68,
                menuLevel:2,
                menuName:'组态看板',
                parentId:69,
                parentMenuName:null,
                subMenu:[]
            },
            {
                menuCode:'data_board',
                menuId:81,
                menuLevel:2,
                menuName:'数据看板',
                parentId:69,
                parentMenuName:null,
                subMenu:[]
            }
        ]
    },
    {
        menuCode:'mach_manage',
        menuId:58,
        menuLevel:1,
        menuName:'设备管理',
        parentId:0,
        parentMenuName:null,
        subMenu:[
            {
                menuCode:'mach_archives',
                menuId:59,
                menuLevel:2,
                menuName:'设备档案',
                parentId:58,
                parentMenuName:null,
                subMenu:[]
            },
            {
                menuCode:'mach_monitor',
                menuId:600,
                menuLevel:2,
                menuName:'运行监控',
                parentId:58,
                parentMenuName:null,
                subMenu:[]
            }
        ]
    },
    {
        menuCode:'cost_manage',
        menuId:60,
        menuLevel:1,
        menuName:'成本监控',
        parentId:0,
        parentMenuName:null,
        subMenu:[
            {
                menuCode:'cost_trend',
                menuId:61,
                menuLevel:2,
                menuName:'成本趋势',
                parentId:60,
                parentMenuName:null,
                subMenu:[]
            },
            {
                menuCode:'cost_calend',
                menuId:62,
                menuName:'成本日历',
                parentId:60,
                parentMenuName:null,
                subMenu:[]
            }
        ]
    },
    {
        menuCode:'analyse_center',
        menuId:63,
        menuLevel:1,
        menuName:'分析中心',
        parentId:0,
        parentMenuName:null,
        subMenu:[
            {
                menuCode:'energy_eff_analyse',
                menuId:64,
                menuLevel:2,
                menuName:'能效分析',
                parentId:63,
                parentMenuName:null,
                subMenu:[]
            },
            // {
            //     menuCode:'fit_analyse',
            //     menuId:65,
            //     menuLevel:2,
            //     menuName:'拟合分析',
            //     parentId:63,
            //     parentMenuName:null,
            //     subMenu:[]
            // },
            {
                menuCode:'energy_conservation_analyse',
                menuId:66,
                menuLevel:2,
                menuName:'节能分析',
                parentId:63,
                parentMenuName:null,
                subMenu:[]
            },
            // {
            //     menuCode:'diagnosis_report',
            //     menuId:67,
            //     menuLevel:2,
            //     menuName:'诊断报告',
            //     parentId:63,
            //     parentMenuName:null,
            //     subMenu:[]
            // }
        ]
    },
    {
        menuCode:'alarm_manage',
        menuId:300,
        menuLevel:1,
        menuName:'告警监控',
        parentId:0,
        parentMenuName:null,
        subMenu:[
            {
                menuCode:'alarm_list',
                menuId:301,
                menuLevel:2,
                menuName:'告警列表',
                parentId:300,
                parentMenuName:''
            },
            {
                menuCode:'alarm_analysis',
                menuId:302,
                menuLevel:2,
                menuName:'告警分析',
                parentId:300,
                parentMenuName:''
            },
            {
                menuCode:'alarm_setting',
                menuId:303,
                menuLevel:2,
                menuName:'告警设置',
                parentId:300,
                parentMenuName:''
            }
        ]
    },
    {
        menuCode:'stat_report',
        menuId:200,
        menuLevel:1,
        menuName:'统计报表',
        parentId:0,
        parentMenuName:null,
        subMenu:[
            {
                menuCode:'cost_report',
                menuId:201,
                menuLevel:2,
                menuName:'成本报表',
                parentId:200,
                parentMenuName:''
            },
            {
                menuCode:'running_report',
                menuId:202,
                menuLevel:2,
                menuName:'运行报表'
            },
            {
                menuCode:'month_report',
                menuId:203,
                menuLevel:2,
                menuName:'月度报告'
            }
        ]
    },
    {
        menuCode:'info_manage',
        menuId:100,
        menuLevel:1,
        menuName:'信息管理',
        parentId:0,
        parentMenuName:null,
        subMenu:[
            {
                menuCode:'free_manage',
                menuId:101,
                menuLevel:2,
                menuName:'计费管理',
                parentId:100,
                parentMenuName:'',
            },
            {
                menuCode:'field_manage',
                menuId:102,
                menuLevel:2,
                menuName:'维度管理',
                parentId:100,
                parentMenuName:'',
            },
            {
                menuCode:'quota_manage',
                menuId:103,
                menuLevel:2,
                menuName:'预算管理',
                parentId:100,
                parentMenuName:''
            }
        ]
    },
    
    {
        menuCode:'system_manage',
        menuId:55,
        menuLevel:1,
        menuName:'系统管理',
        parentId:0,
        parentMenuName:null,
        subMenu:[
            // {
            //     menuCode:'role_manage',
            //     menuId:56,
            //     menuLevel:2,
            //     menuName:'角色权限',
            //     parentId:55,
            //     parentMenuName:null,
            //     subMenu:[
            //         {
            //             menuCode:'add_role',
            //             menuId:57,
            //             menuLevel:9,
            //             menuName:'添加权限',
            //             parentId:56,
            //             parentMenuName:null,
            //             subMenu:[]
            //         }
            //     ]
            // }
            {
                menuCode:'sys_log',
                menuId:400,
                menuLevel:2,
                menuName:'系统日志',
                parentId:55,
                parentMenuName:null
            },
            {
                menuCode:'update_pwd',
                menuId:401,
                menuLevel:2,
                menuName:'修改密码',
                parentId:55,
                parentMenuName:''
            }
        ]
    },
]
const initialState = {
    userInfo: {},
    userMenu: [],
    companyList: [],
    // 全局的公司id
    companyId: '',
    currentCompany: {},
    currentMenu: {},
    // 配置动态路由
    routePath: [],
    routeConfig: {},
    authorized: false,
    isFrame: false,
    // socket实时告警消息
    msg: [],
    agentMsg: {},
    weatherInfo: '',
    // 全局属性告警类型
    alarmTypes: [],
    // 页面总宽度
    containerWidth: 0,
    collapsed: false,
    pagesize: 12,
    
    // 判断是否是中台打开的子窗口
    fromAgent: false,
    // 其他中台商ID，根据这个ID对登录页做特殊判断
    thirdAgent: {},
    newThirdAgent: {},
    // 浅色主题light 深色主题dark
    theme: 'light',
    startDate: moment(date),
    endDate: moment(date),
    timeType: '3',
    
    // 小屏终端下 缩放比例 75%
};

export default {
    namespace: 'user',
    state: initialState,
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen((location) => {
                let pathname = location.pathname;
                // 登录接口
                if (location.pathname === '/login') {
                    // let str = window.location.host.split('.');
                    // let matchResult = agentReg2.exec(str[0]);
                    // let temp = matchResult ? matchResult[1] : '';
                    // dispatch({ type:'fetchNewThirdAgent', payload:temp });
                    // return ;
                }
                if (pathname !== '/login') {
                    new Promise((resolve, reject) => {
                        dispatch({
                            type: 'userAuth',
                            payload: { dispatch, query: location.search, resolve },
                        });
                    }).then(() => {
                        // 更新当前页面路由的路径
                        dispatch({ type: 'setRoutePath', payload: pathname });
                    });
                }
            });
        },
    },
    effects: {
        *userAuth(action, { call, select, put, all }) {
            try {
                let {
                    user: { userInfo, authorized },
                } = yield select();
                let { dispatch, query, resolve, reject } = action.payload || {};
                if (!authorized) {
                    // 判断是否是服务商用户新开的公司标签页
                    let matchResult = companyReg.exec(query);
                    // let companyId = matchResult ? matchResult[2] : localStorage.getItem('companyId') || null;
                    let companyId = matchResult ? matchResult[2] : localStorage.getItem('companyId') || 144;
                    let userId = matchResult ? matchResult[1] : null;
                    let isFrame = matchResult && matchResult[3] === 'frame' ? true : false;
                    let code = qs.parse(query.substring(1, query.length)).code;
                    
                    // 开发环境
                    localStorage.setItem('userId', 2);                 
                    yield put({type:'setUserInfo', payload:{ 
                        data:{
                            userId:localStorage.getItem('userId'),
                            userName:localStorage.getItem('userName'),
                            companyId:localStorage.getItem('companyId'),
                            companyName:localStorage.getItem('companyName'),
                            phone:localStorage.getItem('phone'),
                            menuList:menuMock
                        }, 
                        fromAgent:matchResult ? true : false, 
                        isFrame, 
                    }}); 

                    // 天宫环境 重定向到联通统一认证平台
                    // if ( !code ) {
                    //     window.location.href = 'http://' + ( window.g.apiHost ) + '/admin/sso/checkLogin';
                    //     return ;
                    // } else {
                    //     // 如果还没有过期，直接从缓存读取用户信息
                    //     if ( localStorage.getItem('token')) {
                    //         yield put({type:'setUserInfo', payload:{ 
                    //             data:{
                    //                 userId:localStorage.getItem('userId'),
                    //                 userName:localStorage.getItem('userName'),
                    //                 companyId:localStorage.getItem('companyId'),
                    //                 companyName:localStorage.getItem('companyName'),
                    //                 phone:localStorage.getItem('phone'),
                    //                 menuList:menuMock
                    //             }, 
                    //             fromAgent:matchResult ? true : false, 
                    //             isFrame, 
                    //         }}); 
                    //     } else {
                    //         // 获取登录用户信息
                    //         let data = yield call(userAuth, { code });
                    //         if ( data && data.code === 200 ) {
                    //             let { userId, userName, token, companyId, companyName, phone, menuList } = data.data;
                    //             // console.log(data.data);
                    //             localStorage.setItem('token', token);
                    //             localStorage.setItem('userId', userId);
                    //             localStorage.setItem('userName', userName);
                    //             localStorage.setItem('companyId', companyId);
                    //             localStorage.setItem('companyName', companyName);
                    //             localStorage.setItem('phone', phone);
                    //             yield put({type:'setUserInfo', payload:{ 
                    //                 data:{
                    //                     userId,
                    //                     userName,
                    //                     companyId,
                    //                     companyName,
                    //                     phone,
                    //                     menuList:menuMock
                    //                 }, 
                    //                 fromAgent:matchResult ? true : false, 
                    //                 isFrame
                    //             }});
                    //         }
                    //     }                        
                    // }          
                    yield put({ type: 'setContainerWidth' });
                    // yield put({type:'weather'});                       
                }
                if (resolve && typeof resolve === 'function') resolve();                                     
            } catch (err) {
                console.log(err);
            }
        },
        
        // 中台用户登录时更新当前中台账号下所有企业用户的告警信息
        *updateAgentAlarm(action, { put, call, select }) {
            let { data } = yield call(userAuth);
            if (data && data.code === '0') {
                yield put({ type: 'getAgentAlarm', payload: { data: data.data } });
            }
        },
        *login(action, { call, put, select }) {
            try {
                let { values, resolve, reject } = action.payload || {};
                let { userName, password } = values;
                // password = md5(password, user_name);
                let data = yield call(login, { userName, password, isApp:1 });
                
                if ( data && data.code === 200) {
                    let {
                        companyId,
                        companyName,
                        userName,
                        userId,
                        phone,
                        menuList,
                        token,
                    } = data.data;
                    //  保存登录的时间戳,用户id,公司id
                    localStorage.setItem('companyId', companyId);
                    localStorage.setItem('companyName', companyName);
                    localStorage.setItem('userId', userId);
                    localStorage.setItem('userName', userName);
                    localStorage.setItem('phone', phone);
                    localStorage.setItem('token', token);
                    // localStorage.setItem('menuList', JSON.stringify(menuList || []));
                    localStorage.setItem('menuList', menuMock);
                    //  登录后跳转到默认页面
                    // 跳转到项目列表页
                    yield put(routerRedux.push('/'));
                } else {
                    if (reject) reject(data && data.message);
                }
            } catch (err) {
                console.log(err);
            }
        },
        *weather(action, { call, put }) {
            let { data } = yield call(getWeather);
            if (data && data.code === '0') {
                yield put({ type: 'getWeather', payload: { data: data.data } });
            }
        },
        *loginOut(action, { call, put, select }){
                // 重定向至网信平台的权限验证
                yield put({ type:'clearUserInfo' }); 
                yield put({ type:'fields/reset'});
                yield put(routerRedux.push('/login'));       
            
        },
        // *loginOut(action, { call, put, select }){
        //     let data = yield call(loginOut, { userId:localStorage.getItem('userId')});     
        //     if ( data ) {
        //         // 重定向至网信平台的权限验证
        //         yield put({ type:'clearUserInfo' }); 
        //         yield put({ type:'fields/reset'});
        //         window.location.href = 'http://' + ( window.g.apiHost ) + '/admin/sso/checkLogin';
        //     } else {
        //         console.log( data ? data.message : '');
        //     }
        // },
        
        *fetchNewThirdAgent(action, { put, select, call }) {
            let { data } = yield call(getNewThirdAgent, {
                agent_code: action.payload,
            });
            if (data && data.code === '0') {
                yield put({ type: 'getNewThirdAgent', payload: { data: data.data } });
            } else {
            }
        },

        *changeCompanyLogo(action, { put, call, select }) {
            try {
                let {
                    user: { company_id },
                } = yield select();
                let { logoData, thumbLogoData, resolve, reject } = action.payload || {};
                let { data } = yield call(setCompanyLogo, {
                    company_id,
                    head_logo_path: logoData.filePath,
                    mini_logo_path: thumbLogoData.filePath,
                });
                if (data && data.code === '0') {
                    let {
                        user: { currentCompany },
                    } = yield select();
                    yield put({
                        type: 'updateLogo',
                        payload: {
                            ...currentCompany,
                            head_logo_path: logoData.url,
                            mini_logo_path: thumbLogoData.url,
                        },
                    });
                    if (resolve && typeof resolve === 'function') resolve();
                } else {
                    if (reject && typeof reject === 'function') reject(data.msg);
                }
            } catch (err) {
                console.log(err);
            }
        },
    },
    reducers: {
        setUserInfo(state, { payload: { data, fromAgent, isFrame } }) {
            let { menuList, companyId } = data;
            let currentCompany = null;
            // let currentCompany = company_id ? companys.filter(i=>i.company_id == company_id)[0] : companys[0];
            let routeConfig = menuList.reduce((sum, menu) => {
                sum[menu.menuCode] = {
                    menuName: menu.menuName,
                    menuId: menu.menuId,
                    menuCode: menu.menuCode,
                    children:
                        menu.subMenu && menu.subMenu.length
                            ? menu.subMenu.map((i) => i.menuId)
                            : [],
                };
                //  将菜单和子级菜单生成路由映射表
                if (menu.subMenu && menu.subMenu.length) {
                    menu.subMenu.map((subMenu) => {
                        sum[subMenu.menuCode] = {
                            menuName: subMenu.menuName,
                            menuId: subMenu.menuId,
                            menuCode: subMenu.menuCode,
                            parentId: menu.menuId,
                            btns:subMenu.subMenu
                        };
                    });
                }
                return sum;
            }, {});
            console.log(routeConfig);
            return {
                ...state,
                userInfo: data,
                userMenu: menuList,
                companyId,
                currentCompany: currentCompany || {},
                routeConfig,
                fromAgent,
                authorized: true,
                isFrame,
            };
        },
        setRoutePath(state, { payload }) {
            let routes = payload.split('/').filter((i) => i);
            let { routeConfig } = state;
            // console.log(routeConfig);
            let currentMenu;
            // 默认首页为菜单列表第一项-数据看板页面
            if (payload === '/') {
                let defaultMenu = state.userMenu.length ? state.userMenu[0] : {};
                let defaultSubMenu = defaultMenu.subMenu && defaultMenu.subMenu.length ? defaultMenu.subMenu[0] : {}; 
                currentMenu = routeConfig[defaultSubMenu.menuCode] || {};
                routes = [routeConfig[defaultMenu.menuCode], routeConfig[defaultSubMenu.menuCode]];
                // 实际跳转到菜单列表第一项作为默认首页
                // history.push(`/${defaultMenu.menuCode}/${defaultSubMenu.menuCode}`);
            } else {
                currentMenu = routeConfig[routes[routes.length - 1]]
                    ? routeConfig[routes[routes.length - 1]]
                    : {};

                routes = routes.map((route) => {
                    return routeConfig[route];
                });
            }
            return { ...state, routePath: routes, currentMenu };
        },
        getAgentAlarm(state, { payload: { data } }) {
            return { ...state, userInfo: data };
        },
        getWeather(state, { payload: { data } }) {
            return { ...state, weatherInfo: data };
        },
        setMsg(state, { payload: { data } }) {
            // 根据count 字段判断是否需要更新告警信息
            return { ...state, msg: data };
        },
        setAgentMsg(state, { payload: { data } }) {
            return { ...state, agentMsg: data.detail };
        },
        setContainerWidth(state) {
            let containerWidth = window.innerWidth;
            let containerHeight = window.innerHeight;
            return { ...state, containerWidth };
        },
        toggleTheme(state, { payload }) {
            return { ...state, theme: payload };
        },
        toggleTimeType(state, { payload }) {
            let startDate, endDate;
            let date = new Date();
            if (payload === '3') {
                // 小时维度
                startDate = endDate = moment(date);
            }
            if (payload === '2') {
                // 日维度
                startDate = moment(date).startOf('month');
                endDate = moment(date).endOf('month');
            }
            if (payload === '1') {
                // 月维度
                startDate = moment(date).startOf('year');
                endDate = moment(date).endOf('year');
            }
            if (payload === '4') {
                // 年维度
                startDate = moment(date).subtract(1, 'years').startOf('year');
                endDate = moment(date);
            }
            if (payload === '10') {
                // 周维度  ，调整周的起始日从周日为周一
                startDate = moment(date).startOf('week').add(1, 'days');
                endDate = moment(date).endOf('week').add(1, 'days');
            }
            return { ...state, timeType: payload, startDate, endDate };
        },
        setDate(state, { payload: { startDate, endDate } }) {
            return { ...state, startDate, endDate };
        },
        toggleCollapsed(state) {
            return { ...state, collapsed: !state.collapsed };
        },
        setThirdAgentInfo(state, { payload: { data } }) {
            return { ...state, thirdAgent: data };
        },
        getNewThirdAgent(state, { payload: { data } }) {
            return { ...state, newThirdAgent: data };
        },
        updateLogo(state, { payload }) {
            return { ...state, currentCompany: payload };
        },
        setFromWindow(state, { payload: { timeType, beginDate, endDate } }) {
            return {
                ...state,
                timeType,
                startDate: moment(new Date(beginDate)),
                endDate: moment(new Date(endDate)),
            };
        },
        getAlarmTypesResult(state, { payload: { data } }) {
            return { ...state, alarmTypes: data };
        },
        clearUserInfo(state) {
            localStorage.clear();
            return initialState;
        },
    },
};
